package com.sscaipiao.android.activity.ShuangSeQiu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.sscaipiao.android.R;
import com.sscaipiao.android.activity.HallActivity;
import com.sscaipiao.android.activity.StartTogetherActivity;
import com.sscaipiao.android.common.Constants;
import com.sscaipiao.android.model.User;
import com.sscaipiao.android.utils.CaipiaoServiceHelper;
import com.sscaipiao.android.utils.StringUtil;

public class DoubleColorBallPayActivity extends Activity implements
		OnClickListener, OnItemClickListener {

	private User user;
	private String date;
	private String leftTime;
	private List<String> history;
	private List<String> choosen;
	private int chooseNumber = 0;

	private Button double_color_ball_pay_back;

	private TextView double_color_ball_pay_add_hand;
	private TextView double_color_ball_pay_add_auto;
	private EditText double_color_ball_pay_add_number;
	private EditText double_color_ball_pay_add_date;
	private CheckBox double_color_ball_pay_agree;

	private TextView double_color_ball_pay_together;
	private TextView double_color_ball_pay_total;
	private TextView double_color_ball_pay_sure;

	private TextView protocol;

	private ListView mListView;
	private List<Map<String, Object>> mList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.double_color_ball_pay);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		Intent i = this.getIntent();
		if (!i.equals(null)) {
			Bundle b = i.getExtras();
			if (b != null) {
				if (b.containsKey(Constants.USER)) {
					user = (User) b.get(Constants.USER);
					history = user.getHistory();
					choosen = user.getChoosen();
				}
				if (b.containsKey("date")) {
					//期数
					date = (String) b.get("date");
				}
				if (b.containsKey("leftTime")) {
					leftTime = (String) b.get("leftTime");
				}
			}
		}

		double_color_ball_pay_back = (Button) findViewById(R.id.double_color_ball_pay_back);
		double_color_ball_pay_add_hand = (TextView) findViewById(R.id.double_color_ball_pay_add_hand);
		double_color_ball_pay_add_auto = (TextView) findViewById(R.id.double_color_ball_pay_add_auto);
		double_color_ball_pay_add_number = (EditText) findViewById(R.id.double_color_ball_pay_add_number);
		double_color_ball_pay_add_date = (EditText) findViewById(R.id.double_color_ball_pay_add_date);
		double_color_ball_pay_agree = (CheckBox) findViewById(R.id.double_color_ball_pay_agree);
		double_color_ball_pay_together = (TextView) findViewById(R.id.double_color_ball_pay_together);
		double_color_ball_pay_total = (TextView) findViewById(R.id.double_color_ball_pay_total);
		double_color_ball_pay_sure = (TextView) findViewById(R.id.double_color_ball_pay_sure);
		protocol = (TextView) findViewById(R.id.double_color_ball_pay_regist_txt_protocol);


		double_color_ball_pay_back.setOnClickListener(this);
		double_color_ball_pay_add_hand.setOnClickListener(this);
		double_color_ball_pay_add_auto.setOnClickListener(this);
		double_color_ball_pay_sure.setOnClickListener(this);
		double_color_ball_pay_together.setOnClickListener(this);
		protocol.setOnClickListener(this);

		showChoosen();

		recalculatorTotal();


		double_color_ball_pay_add_number.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
			                              int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				String sAgeFormat1 = getResources().getString(R.string.double_color_ball_add_bottom2);
				if (StringUtil.isNotEmptyString(double_color_ball_pay_add_number.getText().toString()) &&
						StringUtil.isNotEmptyString(double_color_ball_pay_add_date.getText().toString())) {
					double_color_ball_pay_total.setText(String.format(sAgeFormat1, chooseNumber + "",
							Integer.parseInt(double_color_ball_pay_add_number.getText().toString()),
							Integer.parseInt(double_color_ball_pay_add_date.getText().toString()),
							totalMoney()));

				}

			}
		});
		double_color_ball_pay_add_date.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
			                              int after) {


			}

			@Override
			public void afterTextChanged(Editable s) {
				String sAgeFormat1 = getResources().getString(R.string.double_color_ball_add_bottom2);
				if (StringUtil.isNotEmptyString(double_color_ball_pay_add_number.getText().toString()) &&
						StringUtil.isNotEmptyString(double_color_ball_pay_add_date.getText().toString())) {
					double_color_ball_pay_total.setText(String.format(sAgeFormat1, chooseNumber + "",
							Integer.parseInt(double_color_ball_pay_add_number.getText().toString()),
							Integer.parseInt(double_color_ball_pay_add_date.getText().toString()),
							totalMoney()));
				}
			}
		});

	}

	/**
	 *
	 */
	private void showChoosen() {
		mList = new ArrayList<Map<String, Object>>();
		Map<String, Object> mMap = null;
		Log.v("choosen", choosen.size() + "");
		chooseNumber = 0;
		for (int j = 0; j < choosen.size(); j++) {

			mMap = new HashMap<String, Object>();
			Log.v("choosen", choosen.get(j));
			String[] split = choosen.get(j).split(Constants.STRING_SPLITE_COMPLEX);

			mMap.put("double_color_ball_pay_text3", split[0]);
			mMap.put("double_color_ball_pay_text4", split[1].subSequence(0, 2));
			mMap.put("double_color_ball_add_1_or_x", split[2]);
			mMap.put("double_color_ball_add_howmuch", split[3]);
			chooseNumber = chooseNumber + Integer.parseInt(split[3].substring(0, split[3].indexOf("注")));
			mList.add(mMap);
		}

		String[] mFrom = new String[]{"double_color_ball_pay_text3",
				"double_color_ball_pay_text4",
				"double_color_ball_add_1_or_x",
				"double_color_ball_add_howmuch"};

		int[] mTo = new int[]{
				R.id.double_color_ball_pay_text3,
				R.id.double_color_ball_pay_text4,
				R.id.double_color_ball_add_1_or_x,
				R.id.double_color_ball_add_howmuch
		};


		mListView = (ListView) findViewById(R.id.double_color_ball_pay_listView);


		SimpleAdapter mAdapter = new SimpleAdapter(this, mList, R.layout.double_color_ball_pay_item, mFrom, mTo);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);


	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Log.v("onItemClick", arg2 + " " + arg3);
		if (arg2 < choosen.size()) {
			choosen.remove(arg2);
			showChoosen();

			recalculatorTotal();


		}

	}

	@Override
	public void onClick(View v) {
		if (R.id.double_color_ball_pay_back == v.getId()) {

			DoubleColorBallPayActivity.this.finish();

		} else if (R.id.double_color_ball_pay_regist_txt_protocol == v.getId()) {
			new AlertDialog.Builder(this).setTitle("用户投注协议")
					.setMessage(getResources().getString(R.string.user_protocol))
					.setPositiveButton("确定", null)
					.show();

		} else if (R.id.double_color_ball_pay_add_hand == v.getId()) {

			Intent intent = new Intent(DoubleColorBallPayActivity.this, DoubleColorBallActivity.class);
			Bundle b = new Bundle();
			b.putSerializable(Constants.USER, user);
			b.putSerializable("date", date);
			b.putSerializable("leftTime", leftTime);
			intent.putExtras(b);
			startActivity(intent);

		} else if (R.id.double_color_ball_pay_add_auto == v.getId()) {
			if (choosen == null) {
				choosen = new ArrayList<String>();
			}

			String str = randomChoose();

			while (choosen.contains(str)) {
				str = randomChoose();
			}
			choosen.add(str);
			user.setChoosen(choosen);
			showChoosen();

			recalculatorTotal();
		} else if (R.id.double_color_ball_pay_sure == v.getId()) {

			if (chooseNumber <= 0) {
				Toast.makeText(DoubleColorBallPayActivity.this, "请投注", Toast.LENGTH_SHORT).show();
				return;
			} else if (StringUtil.isEmptyString(double_color_ball_pay_add_date.getText().toString()) ||
					Integer.parseInt(double_color_ball_pay_add_date.getText().toString()) < 1 ||
					Integer.parseInt(double_color_ball_pay_add_date.getText().toString()) > 14) {
				Toast.makeText(DoubleColorBallPayActivity.this, "请选择正数期数(1 - 14)", Toast.LENGTH_SHORT).show();
				return;
			} else if (StringUtil.isEmptyString(double_color_ball_pay_add_number.getText().toString()) ||
					Integer.parseInt(double_color_ball_pay_add_number.getText().toString()) < 1) {
				Toast.makeText(DoubleColorBallPayActivity.this, "请选择正数倍数", Toast.LENGTH_SHORT).show();
				return;
			} else if (!double_color_ball_pay_agree.isChecked()) {
				Toast.makeText(DoubleColorBallPayActivity.this, "请阅读并确认 电话购彩协议", Toast.LENGTH_SHORT).show();
				return;
			}

			String retStr = CaipiaoServiceHelper.payLotteryDoubleColorBall(DoubleColorBallPayActivity.this,
					user, date,
					//double_color_ball_pay_add_date.getText().toString(),
					double_color_ball_pay_add_number.getText().toString(),
					totalMoney() / Integer.parseInt(double_color_ball_pay_add_date.getText().toString()) + "");
			String zuihao = Constants.LOGIN_SUCCESS_CODE;
			// 追号 大于 一期 才调用追号接口
			if ((Integer.parseInt(double_color_ball_pay_add_date.getText().toString())) > 1) {
				zuihao = CaipiaoServiceHelper.betZHSSQ(DoubleColorBallPayActivity.this,
						user, date, double_color_ball_pay_add_number.getText().toString(),
						totalMoney() * ((Integer.parseInt(double_color_ball_pay_add_date.getText().toString())) - 1) /
								(Integer.parseInt(double_color_ball_pay_add_date.getText().toString())) + "", null, null);
			}

			if (retStr.startsWith(Constants.LOGIN_SUCCESS_CODE) && zuihao.startsWith(Constants.LOGIN_SUCCESS_CODE)) {
				Toast.makeText(DoubleColorBallPayActivity.this, "购买成功", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(DoubleColorBallPayActivity.this, HallActivity.class);
				Bundle b = new Bundle();
				b.putSerializable(Constants.USER, user);
				intent.putExtras(b);
				startActivity(intent);

			} else {
				Toast.makeText(DoubleColorBallPayActivity.this, retStr.split(Constants.STRING_SPLITE_COMPLEX)[1], Toast.LENGTH_SHORT).show();
				return;
			}

		} else if (R.id.double_color_ball_pay_together == v.getId()) {
			if (Integer.parseInt(double_color_ball_pay_add_date.getText().toString()) > 1) {
				Toast.makeText(DoubleColorBallPayActivity.this, "追号不可以发合买", Toast.LENGTH_SHORT).show();
				return;
			} else {
				Intent intent = new Intent(DoubleColorBallPayActivity.this, StartTogetherActivity.class);
				Bundle b = new Bundle();
				b.putSerializable(Constants.USER, user);
				b.putSerializable("date", date);
				b.putSerializable("totalMoney", totalMoney());
				b.putSerializable("schemeNum1", CaipiaoServiceHelper.combineSchemeNum1(user,
						double_color_ball_pay_add_number.getText().toString(), totalMoney() + ""));
				intent.putExtras(b);
				startActivity(intent);
			}

		}

	}

	/**
	 * @return
	 */
	private int totalMoney() {
		return 2 * chooseNumber * Integer.parseInt(double_color_ball_pay_add_number.getText().toString()) *
				Integer.parseInt(double_color_ball_pay_add_date.getText().toString());
	}

	/**
	 *
	 */
	private void recalculatorTotal() {
		String sAgeFormat1 = getResources().getString(R.string.double_color_ball_add_bottom2);
		double_color_ball_pay_total.setText(String.format(sAgeFormat1, chooseNumber + "",
				Integer.parseInt(double_color_ball_pay_add_number.getText().toString()),
				Integer.parseInt(double_color_ball_pay_add_date.getText().toString()),
				totalMoney()));
	}

	/**
	 * @return
	 */
	private String randomChoose() {
		Integer[] randomRedBalls = StringUtil.getRandom(33, 6);
		Integer[] randomBlueBalls = StringUtil.getRandom(16, 1);

		String redBalls = "";
		String blueBalls = "";
		String singleOrMult = "";

		String sAgeFormat1 = getResources().getString(R.string.double_color_ball_add_1);
		String number = String.format(sAgeFormat1, "1");

		for (int num : randomRedBalls) {
			if (num < 10) {
				redBalls += ("0" + num + Constants.STRING_SPLITE);
			} else {
				redBalls += (num + Constants.STRING_SPLITE);
			}

		}
		for (int num : randomBlueBalls) {
			if (num < 10) {
				blueBalls += ("0" + num + Constants.STRING_SPLITE);
			} else {
				blueBalls += (num + Constants.STRING_SPLITE);
			}

		}

		singleOrMult = getResources().getString(R.string.double_color_ball_add_single);

		String str = redBalls.substring(0, redBalls.length() - 1) + Constants.STRING_SPLITE_COMPLEX +
				blueBalls.substring(0, blueBalls.length() - 1) + Constants.STRING_SPLITE_COMPLEX +
				singleOrMult + Constants.STRING_SPLITE_COMPLEX + number;
		return str;
	}

}
